package mongodbutil

import (
	"app/global"
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 定义全局变量
var (
	clientOptions *options.ClientOptions
	once          sync.Once
	client        *mongo.Client
	ctx           context.Context
	cancel        context.CancelFunc
)

// InitClientOptions 初始化clientOptions的函数
func InitClientOptions() {
	once.Do(func() {
		clientOptions = options.Client().ApplyURI(global.App.Config.DBConf.MongoDBUrl)
		ctx, cancel = context.WithTimeout(context.Background(), 10000*time.Second)

		var err error
		client, err = mongo.Connect(ctx, clientOptions)
		if err != nil {
			log.Fatalf("Failed to connect to MongoDB: %v", err)
		}

		// 检查连接
		err = client.Ping(ctx, nil)
		if err != nil {
			log.Fatalf("Failed to ping MongoDB: %v", err)
		}
	})

}

// 定义一个文档结构体
type Person struct {
	Name  string
	Age   int
	Email string
}

type WebInfo struct {
	Uid             string `json:"uid"`
	Name            string `json:"name"`
	Url             string `json:"url"`
	Weight          int32  `json:"weight"`
	UserId          string `json:"userId"`
	DelFlag         string `json:"delFlag"`
	WebCategoryId   string `json:"webCategoryId"`
	WebCategoryName string `json:"webCategoryName"`
}

func GetList() []WebInfo {
	InitClientOptions()
	// 获取数据库和集合
	collection := client.Database("testdb").Collection("web_info")
	// 查询文档
	filter := bson.M{"webCategoryName": "大模型学习"}

	// 分页参数
	page := 1
	limit := 10
	skip := (page - 1) * limit

	// 配置查询选项
	findOptions := options.Find()
	findOptions.SetSkip(int64(skip))
	findOptions.SetLimit(int64(limit))

	cur, err := collection.Find(ctx, filter, findOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer cur.Close(ctx)

	var results []WebInfo
	if err = cur.All(context.Background(), &results); err != nil {
		log.Fatal(err)
	}

	for _, result := range results {
		fmt.Println(result)
	}
	return results
}

func SearchList(webInfo WebInfo) []WebInfo {
	InitClientOptions()
	// 获取数据库和集合
	collection := client.Database("testdb").Collection("web_info")
	// 查询文档
	filter := bson.M{}
	if webInfo.WebCategoryName != "" {
		filter["webCategoryName"] = webInfo.WebCategoryName
	}
	//filter := bson.M{"webCategoryName": "大模型学习"}

	// 分页参数
	page := 1
	limit := 10
	skip := (page - 1) * limit

	// 配置查询选项
	findOptions := options.Find()
	findOptions.SetSkip(int64(skip))
	findOptions.SetLimit(int64(limit))

	cur, err := collection.Find(ctx, filter, findOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer cur.Close(ctx)

	var results []WebInfo
	if err = cur.All(context.Background(), &results); err != nil {
		log.Fatal(err)
	}
	if results == nil {
		results = make([]WebInfo, 0)
	}
	return results
}

func GetCollection(db string, collection string) (*mongo.Collection, context.Context) {
	InitClientOptions()
	// 获取数据库和集合
	return client.Database(db).Collection(collection), ctx
}
